/**
 * 象限双击放大任务拖动功能测试脚本
 * 在浏览器控制台中运行
 */

// 测试工具类
class FullscreenDragTester {
    constructor() {
        this.testResults = [];
        this.totalTests = 0;
        this.passedTests = 0;
    }
    
    /**
     * 运行测试
     * @param {string} testName 测试名称
     * @param {Function} testFn 测试函数
     */
    async test(testName, testFn) {
        this.totalTests++;
        console.log(`🧪 运行测试: ${testName}`);
        
        try {
            const result = await testFn();
            if (result !== false) {
                this.passedTests++;
                console.log(`✅ ${testName} - 通过`);
                this.testResults.push({ name: testName, status: 'passed', result });
            } else {
                console.log(`❌ ${testName} - 失败`);
                this.testResults.push({ name: testName, status: 'failed', error: 'Test returned false' });
            }
        } catch (error) {
            console.log(`❌ ${testName} - 错误:`, error.message);
            this.testResults.push({ name: testName, status: 'error', error: error.message });
        }
    }
    
    /**
     * 输出测试总结
     */
    summary() {
        console.log('\n📊 测试总结:');
        console.log(`总测试数: ${this.totalTests}`);
        console.log(`通过: ${this.passedTests}`);
        console.log(`失败: ${this.totalTests - this.passedTests}`);
        console.log(`通过率: ${((this.passedTests / this.totalTests) * 100).toFixed(2)}%`);
        
        return {
            total: this.totalTests,
            passed: this.passedTests,
            failed: this.totalTests - this.passedTests,
            rate: (this.passedTests / this.totalTests) * 100,
            results: this.testResults
        };
    }
}

// 创建测试实例
const tester = new FullscreenDragTester();

/**
 * 测试基础功能是否存在
 */
async function testBasicFunctions() {
    // 检查关键函数是否存在
    const requiredFunctions = [
        'openFullscreenModal',
        'closeFullscreenModal', 
        'initFullscreenDragSorting',
        'cleanupFullscreenDragSorting',
        'updateFullscreenTaskOrder',
        'reorderQuadrantTasks',
        'syncFullscreenToMain',
        'validateAllTasksData',
        'repairTasksData'
    ];
    
    for (const funcName of requiredFunctions) {
        if (typeof window[funcName] !== 'function') {
            throw new Error(`缺少必需函数: ${funcName}`);
        }
    }
    
    // 检查全局变量
    if (typeof tasks === 'undefined') {
        throw new Error('缺少全局变量: tasks');
    }
    
    if (typeof quadrantNames === 'undefined') {
        throw new Error('缺少全局变量: quadrantNames');
    }
    
    return true;
}

/**
 * 测试数据完整性验证
 */
async function testDataValidation() {
    const validation = validateAllTasksData();
    
    if (typeof validation !== 'object' || 
        !validation.hasOwnProperty('isValid') ||
        !validation.hasOwnProperty('errors') ||
        !validation.hasOwnProperty('warnings')) {
        throw new Error('数据验证函数返回格式不正确');
    }
    
    console.log('数据验证结果:', validation);
    return validation.isValid;
}

/**
 * 测试全屏模式开启和关闭
 */
async function testFullscreenModal() {
    return new Promise((resolve, reject) => {
        try {
            // 开启全屏模式
            openFullscreenModal('urgent-important');
            
            setTimeout(() => {
                const modal = document.getElementById('fullscreenModal');
                if (!modal.classList.contains('show')) {
                    reject(new Error('全屏模式未正确开启'));
                    return;
                }
                
                // 检查标题是否正确设置
                const title = document.getElementById('fullscreenModalTitle');
                if (title.textContent !== '紧急且重要') {
                    reject(new Error('全屏模式标题设置错误'));
                    return;
                }
                
                // 关闭全屏模式
                closeFullscreenModal();
                
                setTimeout(() => {
                    if (modal.classList.contains('show')) {
                        reject(new Error('全屏模式未正确关闭'));
                        return;
                    }
                    resolve(true);
                }, 100);
            }, 200);
        } catch (error) {
            reject(error);
        }
    });
}

/**
 * 测试拖拽实例管理
 */
async function testDragInstance() {
    return new Promise((resolve, reject) => {
        try {
            // 创建测试任务
            const testTask = {
                id: 99999,
                title: '测试任务',
                description: '用于测试拖拽功能',
                quadrant: 'urgent-important',
                completed: false,
                createdAt: new Date().toLocaleString(),
                order: 0
            };
            
            tasks.push(testTask);
            
            // 开启全屏模式
            openFullscreenModal('urgent-important');
            
            setTimeout(() => {
                // 检查拖拽实例是否创建
                if (!fullscreenSortableInstance) {
                    // 清理测试数据
                    tasks = tasks.filter(t => t.id !== 99999);
                    closeFullscreenModal();
                    reject(new Error('拖拽实例未创建'));
                    return;
                }
                
                // 关闭并检查实例是否清理
                closeFullscreenModal();
                
                setTimeout(() => {
                    if (fullscreenSortableInstance) {
                        // 清理测试数据
                        tasks = tasks.filter(t => t.id !== 99999);
                        reject(new Error('拖拽实例未正确清理'));
                        return;
                    }
                    
                    // 清理测试数据
                    tasks = tasks.filter(t => t.id !== 99999);
                    resolve(true);
                }, 100);
            }, 300);
        } catch (error) {
            // 清理测试数据
            tasks = tasks.filter(t => t.id !== 99999);
            reject(error);
        }
    });
}

/**
 * 测试任务重排序功能
 */
async function testTaskReordering() {
    // 创建测试数据
    const originalTasks = [...tasks];
    const testTasks = [
        { id: 88801, title: '测试任务1', quadrant: 'urgent-important', order: 0, completed: false, createdAt: new Date().toLocaleString() },
        { id: 88802, title: '测试任务2', quadrant: 'urgent-important', order: 1, completed: false, createdAt: new Date().toLocaleString() },
        { id: 88803, title: '测试任务3', quadrant: 'urgent-important', order: 2, completed: false, createdAt: new Date().toLocaleString() }
    ];
    
    try {
        // 添加测试任务
        tasks.push(...testTasks);
        
        // 测试重排序: 将第一个任务移到最后
        reorderQuadrantTasks('urgent-important', 88801, 2);
        
        const reorderedTasks = tasks.filter(t => t.quadrant === 'urgent-important' && t.id >= 88801)
            .sort((a, b) => a.order - b.order);
        
        if (reorderedTasks[0].id !== 88802 || 
            reorderedTasks[1].id !== 88803 || 
            reorderedTasks[2].id !== 88801) {
            throw new Error('任务重排序失败');
        }
        
        // 恢复原始数据
        tasks.length = 0;
        tasks.push(...originalTasks);
        
        return true;
    } catch (error) {
        // 恢复原始数据
        tasks.length = 0;
        tasks.push(...originalTasks);
        throw error;
    }
}

/**
 * 测试错误处理
 */
async function testErrorHandling() {
    try {
        // 测试无效数据处理
        const originalTasks = [...tasks];
        
        // 添加无效数据
        tasks.push({ id: null, title: '', quadrant: 'invalid' });
        
        const validation = validateAllTasksData();
        if (validation.isValid) {
            throw new Error('数据验证未检测到无效数据');
        }
        
        // 测试修复功能
        const repaired = repairTasksData();
        if (!repaired) {
            throw new Error('数据修复失败');
        }
        
        // 恢复原始数据
        tasks.length = 0;
        tasks.push(...originalTasks);
        
        return true;
    } catch (error) {
        throw error;
    }
}

/**
 * 性能测试
 */
async function testPerformance() {
    const start = performance.now();
    
    // 模拟大量数据操作
    const largeTasks = [];
    for (let i = 0; i < 100; i++) {
        largeTasks.push({
            id: 70000 + i,
            title: `性能测试任务 ${i}`,
            quadrant: 'urgent-important',
            order: i,
            completed: false,
            createdAt: new Date().toLocaleString()
        });
    }
    
    const originalTasks = [...tasks];
    tasks.push(...largeTasks);
    
    try {
        // 测试验证性能
        const validation = validateAllTasksData();
        
        // 测试排序性能
        for (let i = 0; i < 10; i++) {
            reorderQuadrantTasks('urgent-important', 70050, Math.floor(Math.random() * 100));
        }
        
        const end = performance.now();
        const duration = end - start;
        
        console.log(`性能测试完成，耗时: ${duration.toFixed(2)}ms`);
        
        // 恢复原始数据
        tasks.length = 0;
        tasks.push(...originalTasks);
        
        // 性能阈值：100个任务的操作应在500ms内完成
        return duration < 500;
    } catch (error) {
        // 恢复原始数据
        tasks.length = 0;
        tasks.push(...originalTasks);
        throw error;
    }
}

/**
 * 运行所有测试
 */
async function runAllTests() {
    console.log('🚀 开始运行象限双击放大任务拖动功能测试\n');
    
    await tester.test('基础功能检查', testBasicFunctions);
    await tester.test('数据完整性验证', testDataValidation);
    await tester.test('全屏模式开启关闭', testFullscreenModal);
    await tester.test('拖拽实例管理', testDragInstance);
    await tester.test('任务重排序功能', testTaskReordering);
    await tester.test('错误处理机制', testErrorHandling);
    await tester.test('性能测试', testPerformance);
    
    const summary = tester.summary();
    
    if (summary.rate >= 85) {
        console.log('\n🎉 测试通过！功能实现良好。');
    } else {
        console.log('\n⚠️  部分测试失败，需要进一步优化。');
    }
    
    return summary;
}

// 导出测试函数供控制台使用
window.runDragTests = runAllTests;
window.FullscreenDragTester = FullscreenDragTester;

console.log('测试脚本已加载。在控制台运行 runDragTests() 开始测试。');